cmake_minimum_required(VERSION 3.13.5)
project(libffi C)

set(SOURCES_LIST
    src/closures.c
    $<$<CONFIG:Debug>:src/debug.c>
    src/java_raw_api.c
    src/prep_cif.c
    src/raw_api.c
    src/tramp.c
    src/types.c)

include(configure_platform.cmake)
include(configure_options.cmake)

file(COPY ${FFI_CONFIG_FILE} DESTINATION ${CMAKE_BINARY_DIR})
file(COPY src/${TARGETDIR}/ffitarget.h DESTINATION ${CMAKE_BINARY_DIR}/include)

include_directories(${CMAKE_BINARY_DIR}/include)
include_directories(${CMAKE_BINARY_DIR})
include_directories(include)

add_definitions(-DFFI_BUILDING)

add_library(objlib OBJECT ${SOURCES_LIST})
set_property(TARGET objlib PROPERTY POSITION_INDEPENDENT_CODE 1)

target_compile_definitions(objlib PUBLIC $<$<CONFIG:Debug>:FFI_DEBUG>)

add_library(ffi_static STATIC $<TARGET_OBJECTS:objlib>)

if(MSVC)
    add_definitions(-DFFI_BUILDING_DLL)
    set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
elseif(CMAKE_SYSTEM_NAME MATCHES Darwin)
    set(CMAKE_MACOSX_RPATH 1)
endif()
add_library(ffi_shared SHARED $<TARGET_OBJECTS:objlib> ${OBJECTS_LIST})

# On Posix systems, libffi.so and libffi.a can co-exist.
if(NOT WIN32 OR CYGWIN)
  set_target_properties(ffi_static PROPERTIES OUTPUT_NAME ffi)
endif()
set_target_properties(ffi_shared PROPERTIES OUTPUT_NAME ffi)

install(TARGETS ffi_static ffi_shared
    EXPORT ${PROJECT_NAME}Targets
    RUNTIME DESTINATION bin
    ARCHIVE DESTINATION lib
    LIBRARY DESTINATION lib)

install(EXPORT ${PROJECT_NAME}Targets
    DESTINATION share/${PROJECT_NAME})

install(FILES
    ${CMAKE_BINARY_DIR}/include/ffi.h
    ${CMAKE_BINARY_DIR}/include/ffitarget.h
    DESTINATION include)
